package net.angrynut.web.handler.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootVersion;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import net.angrynut.web.dao.mapper.UserMapper;
import net.angrynut.web.model.entity.User;

@Controller
@RequestMapping("/hello")
@Slf4j
public class HelloController {

	@Autowired
	private UserMapper userMapper;

	/**
	 * <p>
	 * 演示用在方法上的 {@link org.springframework.web.bind.annotation.ModelAttribute
	 * ModelAttribute}。
	 * </p>
	 * 
	 * <p>
	 * 向 model 中添加一个 attribute。返回值会被添加到 model 下名为 "user" 的 attribute 中。
	 * 你可以这样自定义名字：<tt>@ModelAttribute("myUser")</tt>
	 * </p>
	 */
	@ModelAttribute
	public User addUser(@RequestParam(value = "username", required = false) String username) {
		log.info("1. @ModelAttribute enterred.");
		return username == null ? null : userMapper.findByUsername(username);
	}

	/**
	 * 可分别尝试一下：
	 * <ul>
	 * <li>http://localhost:8192/hello/thymeleaf?username=admin</li>
	 * <li>http://localhost:8192/hello/thymeleaf</li>
	 * </ul>
	 * 
	 * <p>
	 * 同时演示用在方法参数上的 {@link org.springframework.web.bind.annotation.ModelAttribute
	 * ModelAttribute}。说明见 <a href=
	 * "https://segmentfault.com/a/1190000006995458">在方法参数上使用@ModelAttribute注解</a>。
	 * </p>
	 * 
	 */
	@GetMapping("/thymeleaf")
	public ModelAndView thymeleaf(@RequestParam(value = "username", required = false) String username,
			@ModelAttribute("user") User user) {

		log.info("Handler enterred.");
		log.info("Model attribute user is " + JSON.toJSONString(user));

		ModelAndView mav = new ModelAndView("hello.html");
		mav.addObject("username", username);
		mav.addObject("springBootVersion", SpringBootVersion.getVersion());
		return mav;
	}


}
